﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 有限状态机系统管理器
/// </summary>
public class FSMSystem
{
    private FSMState currentState;
    public FSMState CurrentState
    {
        get { return currentState; }
    }

    private Dictionary<StateID, FSMState> states;

    public FSMSystem()
    {
        states = new Dictionary<StateID, FSMState>();
    } 
    /// <summary>
    /// 向状态集添加状态
    /// </summary>
    /// <param name="state"></param>
    public void AddState(FSMState state)
    {
        if (state == null)
        {
            Debug.LogError("状态ID为空");
            return;
        }

        if (states.ContainsKey(state.stateId))
        {
            Debug.LogError("状态已存在");
            return;
        } 
        states.Add(state.stateId, state);
    } 
    /// <summary>
    /// 想状态集移除状态
    /// </summary>
    /// <param name="state"></param>
    public void DelState(FSMState state)
    {
        if (state == null)
        {
            Debug.LogError("状态ID为空");
            return;
        } 
        if (states.ContainsKey(state.stateId)==false)
        {
            Debug.LogError("状态不存在");
            return;
        } 
        states.Remove(state.stateId);
    } 
    public void PerformTransition(Transition trans)
    {
        if (trans == Transition.NullTransition)
        {
            Debug.LogError("空状转换无效");
            return;
        } 
        StateID id = currentState.GetOutputState(trans);
        if (id != StateID.NullStateID)
        {
            FSMState state;
            states.TryGetValue(id ,out state);
            currentState.DoBeforeLeaving();
            currentState = state;
            currentState.DoBeforeEntering();
        }
    }
    /// <summary>
    /// 启动最初状态的方法
    /// </summary>
    public void StartState(StateID id)
    {
        FSMState state;
        states.TryGetValue(id, out state);
        if (state != null)
        {
            state.DoBeforeEntering();
            currentState = state;
        }
    }
}
